package org.cvbpl;

import java.awt.Color;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;

public class Image {
	public final int height, width;
	private final Matrix red;
	private final Matrix blue;
	private final Matrix green;
	
	public Image(int height, int width) {
		this.height = height;
		this.width = width;
		
		red = new Matrix(height, width);
		green = new Matrix(height, width);
		blue = new Matrix(height, width);
	}
	
	public Image(Matrix red, Matrix green, Matrix blue) {
		assert red.height == green.height && green.height == blue.height;
		assert red.width == green.width && green.width == blue.width;
		assert red.height > 0;
		assert red.width > 0;
		
		this.height = red.height;
		this.width = red.width;
		this.red = red;
		this.green = green;
		this.blue = blue;
	}
	
	public static Image load(String file) throws IOException {
		BufferedImage bimg = ImageIO.read(new File(file));
		int width = bimg.getWidth(null);
		int height = bimg.getHeight(null);
		Image image = new Image(width, height);
		
		int[] rgbs = new int[width * height];
		bimg.getRGB(0, 0, width, height, rgbs, 0, width);
		
		for(int col = 0; col < width; col++) {
			for(int row = 0; row < width; row++) {
				Color c = new Color(rgbs[row * width + col]);
				image.red.set(row, col, c.getRed());
				image.green.set(row, col, c.getGreen());
				image.blue.set(row, col, c.getBlue());
			}
		}

		return image;
	}
	
	public void save(String file, String format) throws IOException {
		BufferedImage bimg = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
		for(int row = 0; row < height; row++) {
			for(int col = 0; col < width; col++) {
				Color c = new Color((int) red.get(row, col),
						(int) green.get(row, col),
						(int) blue.get(row, col));
				bimg.setRGB(col, row, c.getRGB());
			}
		}
	    File outputfile = new File(file);
	    ImageIO.write(bimg, format, outputfile);
	}
	
	public Image convolve(Matrix mask) {
		return new Image(red.convolve(mask),
				green.convolve(mask),
				blue.convolve(mask));
	}
}
